<template>
  <div id="mapId"></div>
</template>

<script setup>
import {ref, onMounted} from "vue";

let mapState = null;
let allPointsArr = ref([]);
const initMarksAndInfo = (item) => {
  let marker
  const point = new BMap.Point(item.long, item.lat);
  let labelopts = {
    position: point,
    offset: new BMap.Size(0, 0)
  }
  let label = new BMap.Label(item.organization, labelopts)
  label.setStyle({
    color: '#fff',
    padding: "0 10px",
    fontSize: '14px',
    backgroundColor: 'rgba(0,0,0,0.5)',
    lineHeight: '20px',
    borderRadius: '10px',
    border: '0',
    transform: 'translateX(-50%)',
  })

  // 图标可视区域大小
  // marker点图标
  if (item.src) {
    const icon = item.src;
    const iconSize = new BMap.Size(20, 24);
    const iconUrl = new BMap.Icon(icon, iconSize, {
      // 图标的定位点相对于图标左上角的偏移值
      anchor: new BMap.Size(0, 0),
      // 图标所用的图片的大小
      imageSize: iconSize,
      // 信息窗口开启位置相对于图标左上角的偏移值
      infoWindowAnchor: new BMap.Size(95, 130),
    });
    marker = new BMap.Marker(point, {
      icon: iconUrl,
    });
  }else{
    marker = new BMap.Marker(point);
  }

  marker.addEventListener("click", () => {
    mapState.panTo(new BMap.Point(item.long, item.lat), 500)
    mapState.setZoom(21)
  });

  mapState.addOverlay(label);
  mapState.addOverlay(marker);
};
let initFun = () => {
  // 创建地图实例
  mapState = new BMap.Map("mapId", {
    enableMapClick: false, // 地图底图不可点击
    enableAutoResize: false,
  });
  // 默认成都中心
  mapState.centerAndZoom(new BMap.Point(104.066, 30.663), 14);

  // 地图样式
  mapState.setMapStyle({
    style: "midnight",
  });

  // 可以使用鼠标缩放地图
  mapState.enableScrollWheelZoom(true); // 启用滚轮缩放功能

  // 监听缩放事件，让地图默认移动一下，解决缩放之后某些文字偏移问题
  mapState &&
  mapState.addEventListener("zoomend", (ev) => {
    mapState.panBy(0, 0);
  });
  mapState.clearOverlays();

};

const createMarker = (points) => {
  points.map((item) => {
    initMarksAndInfo(item);
    let point = new BMap.Point(item.long, item.lat);
    allPointsArr.value.push(point);
  });
  setTimeout(() => {
    mapState.setViewport(allPointsArr.value, {margins: [8, 8, 8, 8]});
  }, 500);
}

onMounted(() => {
  initFun();
});

defineExpose({
  createMarker
})
</script>
<style lang="scss" scoped>
#mapId {
  width: 100%;
  height: 100%;
}
</style>
<style lang="scss">
#mapId {
  width: 100%;
  height: 100%;

  .BMap_cpyCtrl,
  .anchorBL {
    display: none;
  }
}
</style>
